package com.d3works.apps.contract.service;

import com.d3works.apps.base.db.Product;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.apps.contract.db.ConsumptionLine;
import com.d3works.apps.contract.db.Contract;
import com.d3works.apps.contract.db.ContractLine;
import com.d3works.apps.contract.db.ContractVersion;
import com.d3works.apps.contract.exception.ContractExceptionMessage;
import com.d3works.auth.AuthUtils;
import com.d3works.auth.db.User;
import com.d3works.i18n.I18n;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import java.util.Optional;

public class ConsumptionLineServiceImpl implements ConsumptionLineService {

  protected AppBaseService appBaseService;

  @Inject
  public ConsumptionLineServiceImpl(AppBaseService appBaseService) {
    this.appBaseService = appBaseService;
  }

  @Override
  public ConsumptionLine fill(ConsumptionLine line, Product product) {
    Preconditions.checkNotNull(product, I18n.get(ContractExceptionMessage.CONTRACT_EMPTY_PRODUCT));
    line.setLineDate(
        appBaseService.getTodayDate(
            Optional.ofNullable(line.getContractLine())
                .map(ContractLine::getContractVersion)
                .map(ContractVersion::getContract)
                .map(Contract::getCompany)
                .orElse(
                    Optional.ofNullable(AuthUtils.getUser())
                        .map(User::getActiveCompany)
                        .orElse(null))));
    line.setProduct(product);
    line.setReference(product.getName());
    line.setUnit(product.getUnit());
    return line;
  }
}
